<template>
  <div class="favorite-goods-tab">
    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ favoriteGoods.length }}</div>
              <div class="stat-label">收藏商品</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Collection /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ totalValue }}</div>
              <div class="stat-label">总价值</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Grid /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ categoryCount }}</div>
              <div class="stat-label">涉及分类</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ averagePrice }}</div>
              <div class="stat-label">平均价格</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <el-row :gutter="16" align="middle">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商品名称"
            clearable
            prefix-icon="Search"
            size="small"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="selectedCategory" placeholder="商品分类" size="small" clearable>
            <el-option label="全部分类" value="" />
            <el-option 
              v-for="category in uniqueCategories" 
              :key="category" 
              :label="category" 
              :value="category" 
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="priceRange" placeholder="价格区间" size="small" clearable>
            <el-option label="全部价格" value="" />
            <el-option label="0-1000元" value="0-1000" />
            <el-option label="1000-5000元" value="1000-5000" />
            <el-option label="5000-10000元" value="5000-10000" />
            <el-option label="10000元以上" value="10000+" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="small" @click="exportFavorites">
            <el-icon><Download /></el-icon>
            导出收藏
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 商品列表 -->
    <div class="goods-section">
      <el-table 
        :data="filteredGoods" 
        border 
        stripe 
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        row-class-name="goods-row"
      >
        <el-table-column prop="idx" label="序号" width="80" align="center" />
        
        <el-table-column label="商品图片" width="120" align="center">
          <template #default="scope">
            <div class="image-container">
              <el-image 
                :src="scope.row.image" 
                :preview-src-list="[scope.row.image]"
                fit="cover"
                class="product-image"
                :initial-index="0"
                :fallback="getFallbackImage(scope.row.category)"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span class="error-text">{{ getCategoryName(scope.row.category) }}</span>
                  </div>
                </template>
              </el-image>
              <div class="image-overlay">
                <el-button size="small" type="primary" circle @click="previewImage(scope.row)">
                  <el-icon><View /></el-icon>
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="商品信息" min-width="300">
          <template #default="scope">
            <div class="product-info">
              <div class="product-name">
                <el-link 
                  type="primary" 
                  :href="`https://www.idora.jp/goods/${scope.row.goodsId}`" 
                  target="_blank"
                  @click="openProductDetail(scope.row)"
                >
                  {{ scope.row.product }}
                </el-link>
              </div>
              <div class="product-meta">
                <el-tag :type="getCategoryTagType(scope.row.category)" size="small">
                  {{ getCategoryName(scope.row.category) }}
                </el-tag>
                <span class="product-id">ID: {{ scope.row.goodsId }}</span>
              </div>
              <div class="product-price">¥{{ formatPrice(scope.row.price) }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="time" label="收藏时间" width="180">
          <template #default="scope">
            <div class="time-info">
              <div class="time-date">{{ formatDate(scope.row.time) }}</div>
              <div class="time-hour">{{ formatTime(scope.row.time) }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="category" label="所属分类" min-width="150">
          <template #default="scope">
            <div class="category-info">
              <el-tag :type="getCategoryTagType(scope.row.category)" size="small">
                {{ getCategoryName(scope.row.category) }}
              </el-tag>
              <div class="category-path">{{ scope.row.category }}</div>
            </div>
          </template>
        </el-table-column>
        

      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="filteredGoods.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, ref, computed } from 'vue';
import { 
  Picture, 
  Star, 
  Collection, 
  Grid, 
  TrendCharts, 
  Search, 
  Download, 
  View 
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const props = defineProps<{ favoriteGoods: any[] }>();

// 响应式数据
const searchKeyword = ref('');
const selectedCategory = ref('');
const priceRange = ref('');
const currentPage = ref(1);
const pageSize = ref(10);

// 计算属性
const totalValue = computed(() => {
  return props.favoriteGoods.reduce((sum, item) => sum + item.price, 0).toLocaleString();
});

const categoryCount = computed(() => {
  const categories = new Set(props.favoriteGoods.map(item => item.category.split('/')[0]));
  return categories.size;
});

const averagePrice = computed(() => {
  if (props.favoriteGoods.length === 0) return '0';
  const total = props.favoriteGoods.reduce((sum, item) => sum + item.price, 0);
  return Math.round(total / props.favoriteGoods.length).toLocaleString();
});

const uniqueCategories = computed(() => {
  const categories = new Set(props.favoriteGoods.map(item => item.category.split('/')[0]));
  return Array.from(categories);
});

const filteredGoods = computed(() => {
  let filtered = props.favoriteGoods;
  
  // 搜索过滤
  if (searchKeyword.value) {
    filtered = filtered.filter(item => 
      item.product.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }
  
  // 分类过滤
  if (selectedCategory.value) {
    filtered = filtered.filter(item => 
      item.category.split('/')[0] === selectedCategory.value
    );
  }
  
  // 价格区间过滤
  if (priceRange.value) {
    filtered = filtered.filter(item => {
      const price = item.price;
      switch (priceRange.value) {
        case '0-1000':
          return price >= 0 && price <= 1000;
        case '1000-5000':
          return price > 1000 && price <= 5000;
        case '5000-10000':
          return price > 5000 && price <= 10000;
        case '10000+':
          return price > 10000;
        default:
          return true;
      }
    });
  }
  
  return filtered;
});

// 方法
function openProductDetail(row: any) {
  console.log('打开商品详情:', row);
  ElMessage.success('正在跳转到商品详情页面...');
}

function getFallbackImage(category: string) {
  const fallbackImages: Record<string, string> = {
    '家电用品': 'https://img.idora.jp/fallback/appliance.jpg',
    '汽车配件': 'https://img.idora.jp/fallback/auto-parts.jpg',
    '收藏品': 'https://img.idora.jp/fallback/collectibles.jpg',
    '电子产品': 'https://img.idora.jp/fallback/electronics.jpg',
    '手机数码': 'https://img.idora.jp/fallback/mobile.jpg',
    '清洁用品': 'https://img.idora.jp/fallback/cleaning.jpg',
    '摩托车配件': 'https://img.idora.jp/fallback/motorcycle.jpg',
    '奔驰配件': 'https://img.idora.jp/fallback/benz.jpg',
    '文具收藏': 'https://img.idora.jp/fallback/stationery.jpg'
  };
  
  const firstCategory = category.split('/')[0];
  return fallbackImages[firstCategory] || fallbackImages[category] || 'https://img.idora.jp/fallback/default.jpg';
}

function getCategoryName(category: string) {
  return category.split('/')[0];
}

function getCategoryTagType(category: string) {
  const categoryTypes: Record<string, string> = {
    '家电用品': 'primary',
    '汽车配件': 'success',
    '收藏品': 'warning',
    '电子产品': 'info',
    '手机数码': 'danger',
    '清洁用品': 'info',
    '摩托车配件': 'success',
    '奔驰配件': 'primary',
    '文具收藏': 'warning'
  };
  
  const firstCategory = category.split('/')[0];
  return categoryTypes[firstCategory] || 'info';
}

function formatPrice(price: number) {
  return price.toLocaleString();
}

function formatDate(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
}

function formatTime(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  });
}

function previewImage(row: any) {
  console.log('预览图片:', row);
}

function removeFavorite(row: any) {
  ElMessage.warning('取消收藏功能开发中...');
}

function exportFavorites() {
  ElMessage.success('导出功能开发中...');
}

function handleSizeChange(size: number) {
  pageSize.value = size;
  currentPage.value = 1;
}

function handleCurrentChange(page: number) {
  currentPage.value = page;
}
</script>

<style scoped>
.favorite-goods-tab {
  padding: 20px;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px;
  color: white;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-card:nth-child(2) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  box-shadow: 0 4px 12px rgba(240, 147, 251, 0.3);
}

.stat-card:nth-child(3) {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
}

.stat-card:nth-child(4) {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  box-shadow: 0 4px 12px rgba(67, 233, 123, 0.3);
}

.stat-icon {
  font-size: 24px;
  opacity: 0.9;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.9;
}

/* 筛选区域样式 */
.filter-section {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

/* 商品列表样式 */
.goods-section {
  margin-bottom: 20px;
}

.goods-row:hover {
  background-color: #f0f9ff !important;
}

.image-container {
  position: relative;
  display: inline-block;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.image-container:hover .product-image {
  transform: scale(1.05);
}

.image-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-name {
  font-weight: 500;
  color: #303133;
  line-height: 1.4;
}

.product-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.product-id {
  color: #909399;
  font-size: 11px;
}

.product-price {
  font-size: 16px;
  color: #f56c6c;
  font-weight: 600;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.time-date {
  font-size: 12px;
  color: #606266;
}

.time-hour {
  font-size: 11px;
  color: #909399;
}

.category-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.category-path {
  font-size: 11px;
  color: #909399;
  line-height: 1.2;
}



.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  background: #f5f7fa;
  color: #c0c4cc;
  border-radius: 8px;
  gap: 4px;
}

.error-text {
  font-size: 10px;
  color: #909399;
  text-align: center;
  line-height: 1;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-section .el-col {
    margin-bottom: 16px;
  }
  
  .filter-section .el-col {
    margin-bottom: 12px;
  }
}
</style> 